//
//  ScrollViewController.swift
//  DemoProject
//
//  Created by hao on 2018/7/18.
//  Copyright © 2018年 hao. All rights reserved.
//

import UIKit

class ScrollViewController: BaseTableViewController {

    let disposeBag = DisposeBag()
    
    lazy var scrollView: UIScrollView = {
        let _scrollView = UIScrollView()
        self.tableHeadView.addSubview(_scrollView)
        _scrollView.addSubview(imageView)
        imageView.frame = self.tableHeadView.bounds
        _scrollView.snp.makeConstraints({ (make) in
            make.left.right.top.bottom.equalTo(0)
        })
        if let size = imageView.image?.size {
            _scrollView.contentSize = size
            imageView.size = size;
        }
        return _scrollView
    }()
    
    let imageView = UIImageView(image: UIImage(named: "UIKit_Struct_Image"))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupData()
        scrollView.rx.contentOffset.asObservable().subscribe(onNext: {
            print(info: "contentOffset: \($0)")
        }).disposed(by: disposeBag)
        // 只设置这两句并没有放大缩小的效果
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 1.5
        // 必须在代理方法 viewForZooming 中返回一个控件对象
        scrollView.delegate = self
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "分页效果", style: .done, target: self, action: #selector(scrollViewPageDemo))
    }
    
    @objc private func scrollViewPageDemo() {
        self.navigationController?.pushViewController(ScrollViewPageDemoController(), animated: true)
    }
    
    // MARK: UIScrollViewDelegate
    override func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        print(info: "scrollView.subviews.count: \(scrollView.subviews.count)")
        return imageView
    }
    
    private func setupData() {
        let titles = ["contentOffset",
                      "contentSize",
                      "contentInset",
                      "bounces",
                      "pagingEnabled",
                      "scrollEnabled",
                      "showsHorizontalScrollIndicator",
                      "showsVerticalScrollIndicator",
                      "minimumZoomScale",
                      "maximumZoomScale",
                      "delegate",
                      "directionalLockEnabled",
                      "decelerationRate",
                      "tracking",
                      "dragging",
                      "delaysContentTouches",
                      "canCancelContentTouches",
                      "indicatorStyle",
                      "decelerating"]
        
        let descArr = ["""
                        默认CGPointZero，用来设置scrollView的滚动偏移量。
                        // 设置scrollView的滚动偏移量
                        scrollView.contentOffset = CGPointMake(0, 200);
                       """,
                       """
                        默认CGSizeZero，用来设置scrollView的滚动范围。
                        // 设置scrollView的滚动范围
                        scrollView.contentSize = CGSizeMake( self.view.bounds.size.width, self.view.bounds.size.height * 2);
                       """,
                       """
                        默认 UIEdgeInsetsZero，用来设置scrollView的额外滚动区域。
                        // 设置scrollView的额外顶部滚动区域:(UIEdgeInsetsMake是逆时针设置，上左下右)
                        scrollView.contentInset = UIEdgeInsetsMake(100, 0, 0, 0);
                       """,
                       """
                        默认为YES，用来设置scrollView的弹簧效果
                        // 取消scrollView的弹簧效果
                        scrollView.bounces = NO;
                       """,
                       """
                        默认为NO，用来设置scrollView是否开启分页.
                        // 开启分页
                        scrollView.pagingEnabled = YES;
                       """,
                       """
                        默认为YES，用来设置scrollView是否允许滚动.
                        // scrollView禁止滚动
                        scrollView.scrollEnabled = NO;
                       """,
                       "默认为YES，用来设置scrollView是否显示水平滚动条",
                       "默认为YES，用来设置scrollView是否显示垂直滚动条",
                       """
                        默认1.0，用来设置scrollView最小缩放比例
                        // 设置scrollView允许子视图的最小缩放比例
                        scrollView.minimumZoomScale = 0.8;
                       """,
                       """
                        默认1.0，用来设置scrollView最大放大比例.
                        // 设置scrollView允许子视图的最大放大比例
                        scrollView.maximumZoomScale = 2;
                       """,
                       """
                        1. 当scrollView的偏移量一改变就会调用这个方法，即滚动scrollView就会调用
                        - (void)scrollViewDidScroll:(UIScrollView *)scrollView;
                        2. 当scrollView缩放时，就会调用这个方法
                        - (void)scrollViewDidZoom:(UIScrollView *)scrollView NS_AVAILABLE_IOS(3_2);

                        3. 即将拖拽的时候调用.
                        - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
                        4. 即将停止拖拽的时候调用
                        - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0);
                        5. 停止拖拽的时候调用。
                        - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;

                        6. 即将减速完成的时候调用
                        - (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView;
                        7. 减速完成的时候调用
                        - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;

                        8. 返回需要缩放哪个视图，这个视图必须是scrollView里的子视图。
                        - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView;

                        // 列如：
                        - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
                            return scrollView.subviews[0];
                        }
                          
                        9. scrollView即将开始缩放
                        - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view NS_AVAILABLE_IOS(3_2);
                        10. scrollView完成缩放
                        - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale;
                        11. 没有开启分页的时候，代理方法调用顺序：
                        scrollViewWillBeginDragging –> scrollViewDidScroll -> scrollViewWillEndDragging -> scrollViewDidEndDragging

                        12. 开启分页的时候，代理方法调用顺序
                        scrollViewWillBeginDragging -> scrollViewDidScroll -> scrollViewDidEndDragging ->scrollViewWillBeginDecelerating ->scrollViewDidScroll -> scrollViewDidEndDecelerating
                       """,
                       "指定控件是否只能在一个方向上滚动",
                       "改变scrollerView的减速点位置",
                       "监控当前目标是否正在被跟踪",
                       "改变scrollerView的减速点位置",
                       "控制视图是否延时调用开始滚动的方法",
                       "控制控件是否接触取消touch的事件",
                       "设定滚动条的样式",
                       "监控当前目标是否正在减速"]
        
        addTitles(titles, footDescs: descArr)
    }

}

// MARK: 展示分页效果
fileprivate class ScrollViewPageDemoController: BaseViewController {
    
    let pageCount = 3
    let disposeBag = DisposeBag()
    
    lazy var scrollView: UIScrollView = {
        let _scrollView = UIScrollView()
        self.view.addSubview(_scrollView)
        _scrollView.frame = self.view.bounds
//        _scrollView.snp.makeConstraints({ (make) in
//            make.left.right.top.bottom.equalTo(0)
//        })
        _scrollView.isPagingEnabled = true
        return _scrollView
    }()
    
    lazy var pageControl: UIPageControl = {
        let _page = UIPageControl()
        self.view.addSubview(_page)
        _page.snp.makeConstraints({ (make) in
            make.centerX.equalTo(self.view)
            make.bottom.equalTo(-44)
        })
        _page.numberOfPages = pageCount
        return _page
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "分页效果"
        let width = scrollView.width
        for i in 0 ..< pageCount {
            let subview = UIView()
            scrollView.addSubview(subview)
            subview.backgroundColor = kRandomColor()
            subview.tag = i
            let x = width*CGFloat(i)
            subview.frame = CGRect(x: x, y: 0, width: width, height: scrollView.height)
        }
        scrollView.contentSize = CGSize(width: width*CGFloat(pageCount), height: scrollView.height)
        // 拖动 scrollview 时切换 pageControl
        scrollView.rx.didEndDecelerating.map({ [weak self] (_) -> Int in
            if let offset = self?.scrollView.contentOffset.x {
                return Int(offset/width)
            }
            return 0
        }).bind(to: pageControl.rx.currentPage).disposed(by: disposeBag)
        
        // 点击 pageControl 切换scrollView
        pageControl.rx.controlEvent(.touchUpInside).map { [weak self] (_) -> CGPoint in
            CGPoint(x: CGFloat(self?.pageControl.currentPage ?? 0)*width, y: 0)
        }.bind(to: scrollView.rx.contentOffset).disposed(by: disposeBag)
//        pageControl.addTarget(self, action: #selector(pageSwitch(_:)), for: .touchUpInside)
    }
    
    @objc private func pageSwitch(_ pageControl: UIPageControl) {
        print(info: "pageControl: \(pageControl), currentPage: \(pageControl.currentPage)")
        let offset = CGPoint(x: CGFloat(pageControl.currentPage)*scrollView.width, y: 0)
        scrollView.contentOffset = offset
    }
    
}

